package com.haoma.aspect;

import cn.hutool.core.date.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * Description: 接口访问切面
 */
@Aspect
@Component
public class RequestAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    // 指定需要加入该注解才进行切面
    @Around("@annotation(com.haoma.annotation.RequestCount)")
    public Object RequestAspectCountAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 获取到请求路径
        String path = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes())
                .getRequest()
                .getRequestURI()
                .toString();
        if (!StringUtils.hasText(path)) {
            return proceedingJoinPoint.proceed();
        }
        // 获取当前日期
        Date date = new Date();
        Object o1 = redisTemplate.opsForValue().get("request-count");
        if (o1 == null) {
            redisTemplate.opsForValue().set("request-count", 0L);
        } else {
            Long aLong = Long.valueOf(o1.toString());
            redisTemplate.opsForValue().set("request-count", aLong + 1);
        }

        String jsonFormat = DateUtil.format(date, "yyyy-MM-dd") + "request";
        // 先查询缓存
        Object o = redisTemplate.opsForHash().get(jsonFormat, path);
        if (o == null) {
            // 存储到Redis中
            redisTemplate.opsForHash().put(jsonFormat, path, 1);
            return proceedingJoinPoint.proceed();
        }
        Integer count = (Integer) o;
        redisTemplate.opsForHash().put(jsonFormat, path, count + 1);
        return proceedingJoinPoint.proceed();
    }
}
